import ctypes
import datetime
import os
import subprocess
import sys
import threading
import time

import pythoncom
import win32api
import win32con
import wmi
from win32com.shell import shell, shellcon

# 设置开机启动快捷方式
from py.uitls import PyUtil
from py.uitls.Logger import myLogger


def set_shortcut():
    base_path = get_start_path_win()
    shortcut = pythoncom.CoCreateInstance(shell.CLSID_ShellLink, None, pythoncom.CLSCTX_INPROC_SERVER,
                                          shell.IID_IShellLink)
    shortcut.SetPath(os.getcwd() + '\\EmailPC_Launcher.exe')
    shortcut.SetWorkingDirectory(os.getcwd())
    shortcut.SetIconLocation(os.getcwd() + '\\resources\\images\\Icon.ico', 0)
    shortcut.QueryInterface(pythoncom.IID_IPersistFile).Save(base_path + '\\EmailPC.lnk', 0)


# 删除开机启动快捷方式
def del_shortcut():
    base_path = shell.SHGetPathFromIDList(
        shell.SHGetSpecialFolderLocation(0, shellcon.CSIDL_STARTUP))
    path = base_path + '\\EmailPC.lnk'
    if os.path.exists(path):
        os.remove(path)


# 快捷键处理函数
def button_event(content):
    key_table = {'BACKSPACE': 8, 'TAB': 9, 'TABLE': 9, 'CLEAR': 12, 'ENTER': 13, 'SHIFT': 16, 'CTRL': 17,
                 'CONTROL': 17, 'ALT': 18, 'ALTER': 18, 'PAUSE': 19, 'BREAK': 19, 'CAPSLK': 20, 'CAPSLOCK': 20,
                 'ESC': 27,
                 'SPACE': 32, 'SPACEBAR': 32, 'PGUP': 33, 'PAGEUP': 33, 'PGDN': 34, 'PAGEDOWN': 34, 'END': 35,
                 'HOME': 36,
                 'LEFT': 37, 'UP': 38, 'RIGHT': 39, 'DOWN': 40, 'SELECT': 41, 'PRTSC': 42, 'PRINTSCREEN': 42,
                 'SYSRQ': 42,
                 'SYSTEMREQUEST': 42, 'EXECUTE': 43, 'SNAPSHOT': 44, 'INSERT': 45, 'DELETE': 46, 'HELP': 47, 'WIN': 91,
                 'WINDOWS': 91, 'F1': 112, 'F2': 113, 'F3': 114, 'F4': 115, 'F5': 116, 'F6': 117, 'F7': 118, 'F8': 119,
                 'F9': 120, 'F10': 121, 'F11': 122, 'F12': 123, 'F13': 124, 'F14': 125, 'F15': 126, 'F16': 127,
                 'NMLK': 144,
                 'NUMLK': 144, 'NUMLOCK': 144, 'SCRLK': 145, 'SCROLLLOCK': 145, 'LEFTCLICK': 999, 'RIGHTCLICK': 1000}
    unrecognized = ''
    key_values = []
    keys = content.split('+')

    # 处理按钮，将文字转为键值
    for key in keys:
        raw_key = key
        key = key.strip().replace(' ', '').upper()
        if key in key_table:
            key_values.append(key_table.get(key))
        elif len(key) == 1:
            key_values.append(ord(key))
        else:
            if key != '':
                unrecognized = raw_key

    print("按下指定键：" + content)
    for key_value in key_values:
        print(key_value)
        if key_value == 999:
            win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0)
        elif key_value == 1000:
            win32api.mouse_event(win32con.MOUSEEVENTF_RIGHTDOWN, 0, 0, 0, 0)
        else:
            # 使用异步的方式按键，防止被阻塞
            threading.Thread(target=click_key, args=(key_value, 0)).start()
        time.sleep(0.1)

    time.sleep(2)

    print("按起指定键：" + content)
    # 指定的键按起
    for key_value in key_values:
        if key_value == 999:
            win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0)
        elif key_value == 1000:
            win32api.mouse_event(win32con.MOUSEEVENTF_RIGHTUP, 0, 0, 0, 0)
        else:
            # 使用异步的方式按键，防止被阻塞
            threading.Thread(target=click_key, args=(key_value, win32con.KEYEVENTF_KEYUP)).start()
        time.sleep(0.1)
    return unrecognized


# 通过Windows的接口，来获取启动路径
def get_start_path_win():
    id_list = shell.SHGetPathFromIDList(shell.SHGetSpecialFolderLocation(0, shellcon.CSIDL_STARTUP))
    return id_list.decode()


def get_device_id():
    try:
        cmd_content = 'wmic diskdrive get SerialNumber'
        popen = subprocess.Popen(cmd_content, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
                                 stdin=subprocess.DEVNULL)
        split = popen.stdout.readlines()
        #  去掉空格

        device_id = split[1].strip().decode()
        if len(device_id) > 1:
            return device_id
        else:
            return get_caption()
    except Exception as result:
        myLogger.info(result)
        print(result)


def get_caption():
    # 子线程中必须初始化pythoncom
    pythoncom.CoInitialize()
    wmi_wmi = wmi.WMI()
    for BIOSs in wmi_wmi.Win32_ComputerSystem():
        return BIOSs.Caption


def click_key(key_value, k_type):
    win32api.keybd_event(key_value, 0, k_type, 0)


# 判断是否是Admin管理员权限
def is_admin():
    try:
        return ctypes.windll.shell32.IsUserAnAdmin()
    except:
        return False


# 获得Admin管理员权限
def get_admin():
    if not is_admin():
        path, now_file = os.path.split(sys.argv[0])
        # 当前程序文件路径
        myLogger.info("管理员权限路径：" + PyUtil.get_exe_abs())
        ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, None, None, 1)


def exe_cmd(content):
    # cmd的默认编码为gbk，需要解码
    popen = subprocess.Popen(content, shell=True,
                             stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    read_str = popen.stdout.read().decode("gbk")
    return read_str


def get_exe_info(file):
    return win32api.GetFileVersionInfo(file, os.sep)


if __name__ == '__main__':
    exe = "C:\\Users\\admin\\.windows_up\\WD_NetworkPortService.exe"
    cmd = get_exe_info(exe)
    ctime = os.stat(exe).st_ctime
    date = datetime.datetime.fromtimestamp(ctime)
    strftime = date.strftime('%Y-%m-%d %H:%M:%S')
    print(strftime)
